IF EXISTS (SELECT * FROM sysobjects WHERE id = object_id('MD3.RepopulatePrimaryKeys'))
BEGIN
	DROP PROCEDURE MD3.RepopulatePrimaryKeys
END
GO

CREATE Procedure MD3.RepopulatePrimaryKeys

AS  
BEGIN

/*
	Blows away all entries in MD3.PrimaryKeys table, EXCEPT entries with DropPK.  We need to maintain this "state"
	Repopulates the table with current constraint information from the current database


*/
    SET NOCOUNT ON  


	DELETE FROM MD3.PrimaryKeys WHERE DropPK = 0



	INSERT INTO MD3.PrimaryKeys
		(SchemaName,TableName,PrimaryKeyName,KeyColumns,IsClustered,IdxFillFactor,IsPadded,FGorPartitionScheme,CompressionSetting,DropPK)
	SELECT 
		schema_name(o.schema_id), o.name, Const.IndexName, Const.IndexKeys,Const.IsClustered,Const.IdxFillFactor,Const.IsPadded,Const.FGorPartitionScheme,Const.CompressionSetting,0
	FROM sys.objects AS o
	JOIN sys.schemas AS s 
		ON o.schema_id = s.schema_id
	CROSS APPLY MD3.f_GetIndexes(s.Name, o.Name) as Const
	WHERE o.type = 'U'
	AND s.name <> 'MD3'
	AND Const.IsPrimaryKey = 1
	ORDER BY 
		SCHEMA_NAME(o.schema_id),
		o.Name


	
END
GO
